package com.pencilisland.pay.mgt.console.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.pencilisland.pay.mgt.console.bean.ConstantVars;
import com.pencilisland.pay.mgt.console.service.UserService;
import com.pencilisland.pay.mgt.util.G;

/**
 * 自定义扩展表单验证过滤器
 * 
 * @author Breeze
 * 
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
	@Autowired
	UserService userService;

	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if(SecurityUtils.getSubject().getSession().getAttribute(ConstantVars.SESSION_SHIRO_USER)==null){
			WebUtils.toHttp(response).setHeader("sessionstatus", "unauth");
		}
		
		return super.onAccessDenied(request, response);
	}


	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		log.info("用户[{}]登录成功",G.str(token.getPrincipal()));
		subject.getSession().setAttribute(ConstantVars.SESSION_SHIRO_USER, userService.findByLoginName(G.str(token.getPrincipal())));
		return super.onLoginSuccess(token, subject, request, response);
	}

}
